//
//  DaumMapParser.m
//  Tag-C
//
//  Created by KyuJin on 13. 2. 9..
//  Copyright (c) 2013년 monscape. All rights reserved.
//

#import "DaumMapParser.h"

static DaumMapParser* _instance;

@implementation DaumMapParser

#pragma mark - Singleton Function
+ (DaumMapParser*) getInstance
{
    if(!_instance)
    {
        _instance = [[DaumMapParser alloc] init];
    }
    
    return _instance;
}

#pragma mark - Getter Function
- (MTMapPointPlain) getCoodFromTradeName:(NSString*)location
{
    MTMapPointPlain retValue = MTMapPointPlainMake(-1, -1);
    
    NSString *locationURL = [NSString stringWithFormat:TRADE_URL, [location stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
    
    TreeNode *parseData = [[self parseSearchXmlData:locationURL searchType:SEARCH_TYPE_TRADE] objectAtIndex:0];
    
    if(parseData != nil)
    {
        for(TreeNode *item in [parseData objectsForKey:@"item"])
        {
            retValue.x = [[[item objectForKey:@"mapx"] leafvalue] doubleValue];
            retValue.y = [[[item objectForKey:@"mapy"] leafvalue] doubleValue];
        }
    }
    
    retValue = [self convertKTMtoWCONG:retValue];
    
    return retValue;
}

- (MTMapPointPlain) getCoodFromAddress:(NSString*)location
{
    MTMapPointPlain retValue = MTMapPointPlainMake(-1, -1);
    
    NSString *locationURL = [NSString stringWithFormat:ADDRESS_URL, [location stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
    
    TreeNode *parseData = [[self parseSearchXmlData:locationURL searchType:SEARCH_TYPE_ADDRESS] objectAtIndex:0];
    
    if(parseData != nil)
    {
        for(TreeNode *point in [parseData objectsForKey:@"point"])
        {
            retValue.x = [[[point objectForKey:@"x"] leafvalue] doubleValue];
            retValue.y = [[[point objectForKey:@"y"] leafvalue] doubleValue];
        }
    }
    
    retValue = [self convertKTMtoWCONG:retValue];
    
    return retValue;
}

- (TreeNode*) getTradeSearchResult:(NSString*)location
{
    NSString *locationURL = [NSString stringWithFormat:TRADE_URL, [location stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
    
    return [[self parseSearchXmlData:locationURL searchType:SEARCH_TYPE_TRADE] objectAtIndex:0];
}

- (TreeNode*) getAddressSearchResult:(NSString*)location
{
    NSString *locationURL = [NSString stringWithFormat:ADDRESS_URL, [location stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
    
    return [[self parseSearchXmlData:locationURL searchType:SEARCH_TYPE_ADDRESS] objectAtIndex:0];
}

- (NSString*) getRouteJsonString:(NSString*)startName eName:(NSString*)endName sPoint:(MTMapPointPlain)startPoint ePoint:(MTMapPointPlain)endPoint
{
    NSString *URL = [[NSString stringWithFormat:ROUTE_SEARCH_URL, startName, startPoint.x, startPoint.y, endName, endPoint.x, endPoint.y] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    
    NSLog(@"%@", URL);
    
    NSString *retValue = [NSString stringWithContentsOfURL:[NSURL URLWithString:URL] encoding:NSUTF8StringEncoding error:nil];
    NSRange prefix = [retValue rangeOfString:@"("];
    
    retValue = [retValue substringFromIndex:prefix.length + prefix.location];
    retValue = [retValue substringToIndex:retValue.length - 1];
    
    return retValue;
}

- (NSInteger) getTaxiCost:(NSDictionary*)jsonData
{
    return [[NSString stringWithFormat:@"%@",[[jsonData objectForKey:@"car"] objectForKey:@"expectedTaxiCost"]] integerValue];
}

- (NSInteger) getExpectedTime:(NSDictionary*)jsonData
{
    return [[NSString stringWithFormat:@"%@",[[jsonData objectForKey:@"car"] objectForKey:@"expectedTime"]] integerValue];
}

- (double) getDistance:(NSDictionary*)jsonData
{
    return [[NSString stringWithFormat:@"%@",[[jsonData objectForKey:@"car"] objectForKey:@"totalLength"]] doubleValue];
}

#pragma mark - Data Function
- (NSDictionary*) parseMapJsonData:(NSString*)jsonString
{
    NSDictionary *retValue = nil;
    NSError *error = nil;
    
    @try {
        retValue = [[NSJSONSerialization JSONObjectWithData:[jsonString dataUsingEncoding:NSUTF8StringEncoding] options:kNilOptions error:&error] copy];
    }
    @catch (NSException *exception) {
        NSLog(@"%@", exception.reason);
    }
    @finally {
        return retValue;
    }
}

- (NSArray*) parseSearchXmlData:(NSString*)xmlData searchType:(SEARCH_TYPE)type
{
    TreeNode *root = [[XMLParser sharedInstance] parseXMLFromURL:[NSURL URLWithString:xmlData]];
    NSArray *parseData = nil;
    
    if(root != nil)
    {
        switch (type)
        {
            case SEARCH_TYPE_TRADE:
                parseData = [[root objectsForKey:@"channel"] copy];
                break;
                
            case SEARCH_TYPE_ADDRESS:
                parseData = [[root objectsForKey:@"item"] copy];
                break;
                
            default:
                break;
        }
    }
    
    return parseData;
}

- (MTMapPointPlain) convertKTMtoWCONG:(MTMapPointPlain)cood
{
    MTMapPointPlain retValue = MTMapPointPlainMake(-1, -1);
    
    @try {
        // 좌표 변환 (네이버(KTM)->다음(W콩나물))
        NSString *webUrl = [NSString stringWithFormat:CONVERT_URL, cood.x, cood.y];
        
        NSString *jsonString = [NSString stringWithContentsOfURL:[NSURL URLWithString:webUrl]
                                                        encoding:NSUTF8StringEncoding
                                                           error:nil];
        
        NSError *error = nil;
        NSDictionary *coodDict = [NSJSONSerialization JSONObjectWithData:[jsonString dataUsingEncoding:NSUTF8StringEncoding]
                                                                 options:kNilOptions
                                                                   error:&error];
        
        retValue.y = [[coodDict objectForKey:@"y"] doubleValue];
        retValue.x = [[coodDict objectForKey:@"x"] doubleValue];
    }
    @catch (NSException *exception) {
        NSLog(@"%@", exception.reason);
    }
    @finally {
        return retValue;
    }
}

#pragma mark - Map Control Function
- (void) addRoutePolyLine:(MTMapView*)mapView json:(NSDictionary*)jsonData
{
    NSMutableArray *linksArray = [[[NSMutableArray alloc] init] autorelease];
    
    MTMapPolyline *polyLine = [MTMapPolyline polyLine];
    polyLine.tag = 1000;
    polyLine.polylineColor = [UIColor colorWithRed:1.0f green:0.2f blue:0.0f alpha:0.5f];
    
    for(NSDictionary *links in [[[[jsonData objectForKey:@"car"] objectForKey:@"sections"] objectAtIndex:0] objectForKey:@"links"])
    {
        [linksArray addObject:[[links objectForKey:@"points"] componentsSeparatedByString:@","]];
    }
    
    for(NSArray *pointArray in linksArray)
    {
        for(NSString *pointString in pointArray)
        {
            NSArray *point = [pointString componentsSeparatedByString:@" "];
            [polyLine addPoint:[MTMapPoint mapPointWithWCONG:MTMapPointPlainMake(
                                                                                 [[point objectAtIndex:0] doubleValue],
                                                                                 [[point objectAtIndex:1] doubleValue]
                                                                                 )]];
        }
    }
    
    [mapView performSelectorOnMainThread:@selector(addPolyline:) withObject:polyLine waitUntilDone:YES];
    [mapView performSelectorOnMainThread:@selector(fitMapViewAreaToShowAllPolylines) withObject:polyLine waitUntilDone:YES];
}

- (void) addStartPOIItem:(MTMapView*)mapView point:(MTMapPointPlain)startPoint
{
    MTMapPOIItem* existingPOIItemStart = [mapView findPOIItemByTag:10001];
    if (existingPOIItemStart != nil) {
        [mapView removePOIItem:existingPOIItemStart];
    }
    
    MTMapPOIItem* poiItemStart = [MTMapPOIItem poiItem];
    poiItemStart.itemName = @"출발";
    poiItemStart.tag = 10001;
    poiItemStart.mapPoint = [MTMapPoint mapPointWithWCONG:MTMapPointPlainMake(startPoint.x, startPoint.y)];
    poiItemStart.markerType = MTMapPOIItemMarkerTypeCustomImage;
    poiItemStart.showAnimationType = MTMapPOIItemShowAnimationTypeSpringFromGround;
    poiItemStart.customImageName = @"custom_poi_marker_start.png";
    poiItemStart.customImageAnchorPointOffset = MTMapImageOffsetMake(42,2);
    
    [mapView performSelectorOnMainThread:@selector(addPOIItem:) withObject:poiItemStart waitUntilDone:YES];
}

- (void) addEndPOIItem:(MTMapView*)mapView point:(MTMapPointPlain)endPoint
{
    MTMapPOIItem* existingPOIItemEnd = [mapView findPOIItemByTag:10002];
    if (existingPOIItemEnd != nil) {
        [mapView removePOIItem:existingPOIItemEnd];
    }
    
    MTMapPOIItem* poiItemEnd = [MTMapPOIItem poiItem];
    poiItemEnd.itemName = @"도착";
    poiItemEnd.tag = 10002;
    poiItemEnd.mapPoint = [MTMapPoint mapPointWithWCONG:MTMapPointPlainMake(endPoint.x, endPoint.y)];
    poiItemEnd.markerType = MTMapPOIItemMarkerTypeCustomImage;
    poiItemEnd.showAnimationType = MTMapPOIItemShowAnimationTypeSpringFromGround;
    poiItemEnd.customImageName = @"custom_poi_marker_end.png";
    poiItemEnd.customImageAnchorPointOffset = MTMapImageOffsetMake(42,2);
    
    [mapView performSelectorOnMainThread:@selector(addPOIItem:) withObject:poiItemEnd waitUntilDone:YES];
}

@end
